import 'package:craze/common/index.dart';
import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class ProtectionView extends StatefulWidget {
  final String? activityId;

  const ProtectionView({super.key, this.activityId});

  @override
  State<ProtectionView> createState() => _ProtectionViewState();
}

class _ProtectionViewState extends State<ProtectionView> {
  // 获取store
  final MarineProtectionStore _marineProtectionStore =
      getIt<MarineProtectionStore>();
  final AuthStore _authStore = getIt<AuthStore>();

  // 当前活动
  MarineProtectionModel? _currentActivity;

  // 用户的提交记录
  UserSubmissionModel? _userSubmission;

  // 对应的表情
  EmojiModel? _relatedEmoji;

  // 选择的图片
  File? _selectedImage;
  AssetEntity? _selectedAsset;

  // 是否正在上传
  bool _isUploading = false;

  @override
  void initState() {
    super.initState();

    // 加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
    });
  }

  // 加载数据
  Future<void> _loadData() async {
    // 加载活动
    await _marineProtectionStore.loadActivities();

    // 加载表情
    await _marineProtectionStore.loadEmojis();

    // 如果已登录，加载用户提交记录
    if (_authStore.isLoggedIn) {
      await _marineProtectionStore.loadUserSubmissions();
    }

    // 获取当前活动
    if (widget.activityId != null) {
      _findCurrentActivity(widget.activityId!);
    } else if (_marineProtectionStore.activities.isNotEmpty) {
      _findCurrentActivity(_marineProtectionStore.activities.first.id);
    }
  }

  // 查找当前活动
  void _findCurrentActivity(String activityId) {
    try {
      _currentActivity = _marineProtectionStore.activities.firstWhere(
        (activity) => activity.id == activityId,
      );

      // 查找相关的表情
      _relatedEmoji = _marineProtectionStore.emojis.firstWhere(
        (emoji) => emoji.id == _currentActivity!.rewardEmojiId,
      );

      // 如果已登录，查找用户是否已提交
      if (_authStore.isLoggedIn) {
        try {
          _userSubmission = _marineProtectionStore.userSubmissions.firstWhere(
            (submission) => submission.activityId == activityId,
          );
        } catch (e) {
          _userSubmission = null;
        }
      }

      setState(() {});
    } catch (e) {
      print('找不到活动: $e');
    }
  }

  // 选择图片
  Future<void> _pickImage() async {
    if (!_authStore.isLoggedIn) {
      // 显示登录提示对话框
      await LoginDialog.show(
        context,
        title: 'Login Required',
        description: 'You need to login to participate in this activity.',
      );
      return;
    }

    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        themeColor: MyColors.blue,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final File? file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedAsset = result.first;
          _selectedImage = file;
        });
      }
    }
  }

  // 上传图片
  Future<void> _uploadImage() async {
    if (_selectedImage == null || _currentActivity == null) return;

    setState(() {
      _isUploading = true;
    });

    try {
      final loading = MyToast.showLoading(context, 'Saving image...');

      // 保存图片到本地应用目录
      final savedImagePath = await _saveImageToLocal(_selectedImage!);

      if (savedImagePath == null) {
        throw Exception('Failed to save activity image');
      }

      MyToast.dismiss(loading);

      // 使用永久保存的图片路径提交活动
      final bool success = await _marineProtectionStore.submitToActivity(
        _currentActivity!.id,
        savedImagePath,
      );

      if (success) {
        // 上传成功，重新加载数据
        await _loadData();

        // 显示成功提示
        if (mounted) {
          MyToast.showSuccess(
            context,
            'Congratulations! You\'ve unlocked a new emoji!',
          );
        }
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        MyToast.showError(context, 'Failed to upload image: $e');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isUploading = false;
        });
      }
    }
  }

  // 检查表情是否已解锁
  bool _isEmojiUnlocked() {
    return _relatedEmoji?.isUnlocked ?? false;
  }

  // 保存图片到本地应用目录
  Future<String?> _saveImageToLocal(File imageFile) async {
    try {
      // 获取应用文档目录
      final appDir = await getApplicationDocumentsDirectory();
      // 创建保存活动图片的子目录
      final activityImagesDir = Directory('${appDir.path}/activity_images');
      if (!await activityImagesDir.exists()) {
        await activityImagesDir.create(recursive: true);
      }

      // 生成唯一文件名
      final fileName =
          'activity_${DateTime.now().millisecondsSinceEpoch}${path.extension(imageFile.path)}';
      final savedImagePath = '${activityImagesDir.path}/$fileName';

      // 复制图片到新目录
      final newImage = await imageFile.copy(savedImagePath);

      // 返回保存的路径
      return newImage.path;
    } catch (e) {
      if (mounted) {
        MyToast.showError(context, 'Failed to save image: ${e.toString()}');
      }
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Observer(
              builder: (_) {
                if (_marineProtectionStore.isLoading) {
                  return Center(child: CircularProgressIndicator());
                }

                return SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          GestureDetector(
                            onTap: () {
                              GoRouter.of(context).pop();
                            },
                            child: Icon(
                              MyIcons.iconBack,
                              size: 24,
                              color: Colors.white,
                            ),
                          ),
                          Expanded(
                            child: Center(
                              child: Text(
                                'Details',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 22.sp,
                                  fontFamily:
                                      GoogleFonts.mochiyPopOne().fontFamily,
                                  fontWeight: FontWeight.w400,
                                  height: 1.36,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 20.h),

                      Text(
                        _currentActivity?.title ?? 'Clean up marine debris.',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.39,
                        ),
                      ),

                      SizedBox(height: 20.h),

                      Row(
                        children: [
                          // 点
                          Container(
                            width: 8.w,
                            height: 8.w,
                            decoration: BoxDecoration(
                              color: MyColors.blue,
                              shape: BoxShape.circle,
                            ),
                          ),

                          SizedBox(width: 6.w),

                          Text(
                            'About this activity',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18.sp,
                              fontFamily: GoogleFonts.inter().fontFamily,
                              fontWeight: FontWeight.w600,
                              height: 1.17,
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 10.h),

                      // 保护详情信息
                      Text(
                        _currentActivity?.description ??
                            'Reduce marine garbage pollution, protect clean water environment, and restore vitality and purity to every piece of blue.',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontFamily: GoogleFonts.inter().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.50,
                        ),
                      ),

                      SizedBox(height: 20.h),

                      Row(
                        children: [
                          // 点
                          Container(
                            width: 8.w,
                            height: 8.w,
                            decoration: BoxDecoration(
                              color: MyColors.blue,
                              shape: BoxShape.circle,
                            ),
                          ),

                          SizedBox(width: 6.w),
                          Text(
                            'Activity Rewards',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18.sp,
                              fontFamily: GoogleFonts.inter().fontFamily,
                              fontWeight: FontWeight.w600,
                              height: 1.17,
                            ),
                          ),
                        ],
                      ),

                      Text(
                        'Upload pictures to complete tasks, receive emoticon packs, and then you can have fun chatting with friends on the chat page.',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontFamily: GoogleFonts.inter().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.50,
                        ),
                      ),

                      SizedBox(height: 20.h),

                      GestureDetector(
                        onTap: () {
                          MyToast.showSuccess(
                            context,
                            'Accept activity successfully！',
                          );
                        },
                        child: AspectRatio(
                          aspectRatio: 374 / 164.39,
                          child: Container(
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage(MyImages.activityBg),
                                fit: BoxFit.contain,
                              ),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                // 表情 - 根据解锁状态显示不同颜色
                                Transform.translate(
                                  offset: Offset(-50.w, 0.h),
                                  child: SizedBox(
                                    width: 98.w,
                                    height: 98.w,
                                    child:
                                        _relatedEmoji != null
                                            ? ColorFiltered(
                                              colorFilter: ColorFilter.mode(
                                                _isEmojiUnlocked()
                                                    ? Colors.transparent
                                                    : Colors.black.withAlpha(
                                                      100,
                                                    ),
                                                BlendMode.srcATop,
                                              ),
                                              child: Image.asset(
                                                _relatedEmoji!.path,
                                                fit: BoxFit.contain,
                                              ),
                                            )
                                            : Image.asset(
                                              MyImages.love,
                                              fit: BoxFit.contain,
                                              color: Colors.grey,
                                            ),
                                  ),
                                ),

                                Transform.translate(
                                  offset: Offset(-20.w, 0.h),
                                  child: SizedBox(
                                    width: 171.42.w,
                                    height: 33.53.h,
                                    child: ColorFiltered(
                                      colorFilter: ColorFilter.mode(
                                        _isEmojiUnlocked()
                                            ? Colors.transparent
                                            : Colors.black.withAlpha(100),
                                        BlendMode.srcATop,
                                      ),
                                      child: Image.asset(
                                        MyImages.receive,
                                        fit: BoxFit.contain,
                                      ),
                                    ),
                                  ),
                                ),

                                SizedBox(height: 3.h),
                              ],
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: 20.h),

                      Text(
                        'Upload event pictures',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                          height: 1.39,
                        ),
                      ),

                      SizedBox(height: 20.h),

                      // 图片上传区域
                      GestureDetector(
                        onTap:
                            _userSubmission != null || _isEmojiUnlocked()
                                ? null // 已提交或已解锁，禁用点击
                                : _pickImage,
                        child: Container(
                          height: 256.h,
                          decoration: ShapeDecoration(
                            gradient: LinearGradient(
                              begin: Alignment(0.50, 0.00),
                              end: Alignment(0.50, 0.86),
                              colors: [
                                const Color(0xFF0076FF).withAlpha(60),
                                const Color(0xFF045EC6).withAlpha(60),
                              ],
                            ),
                            shape: RoundedRectangleBorder(
                              side: BorderSide(
                                width: 1,
                                color: const Color(0xFF0076FF),
                              ),
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                          ),
                          child:
                              _selectedImage != null
                                  ? Stack(
                                    alignment: Alignment.center,
                                    children: [
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                        child:
                                            _selectedAsset != null
                                                ? AssetEntityImage(
                                                  _selectedAsset!,
                                                  isOriginal: false,
                                                  fit: BoxFit.cover,
                                                  width: double.infinity,
                                                  height: double.infinity,
                                                )
                                                : Image.file(
                                                  _selectedImage!,
                                                  fit: BoxFit.cover,
                                                  width: double.infinity,
                                                  height: double.infinity,
                                                ),
                                      ),
                                      // 上传按钮
                                      if (!_isUploading &&
                                          _userSubmission == null &&
                                          !_isEmojiUnlocked())
                                        Positioned(
                                          bottom: 16,
                                          child: ElevatedButton(
                                            onPressed: _uploadImage,
                                            style: ElevatedButton.styleFrom(
                                              backgroundColor: MyColors.blue,
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(20.r),
                                              ),
                                              padding: EdgeInsets.symmetric(
                                                horizontal: 24.w,
                                                vertical: 10.h,
                                              ),
                                            ),
                                            child: Text(
                                              'Upload',
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontFamily:
                                                    GoogleFonts.mochiyPopOne()
                                                        .fontFamily,
                                              ),
                                            ),
                                          ),
                                        ),
                                      // 加载指示器
                                      if (_isUploading)
                                        CircularProgressIndicator(
                                          color: Colors.white,
                                        ),
                                    ],
                                  )
                                  : _userSubmission != null
                                  ? Stack(
                                    alignment: Alignment.center,
                                    children: [
                                      // 显示已提交的图片
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                        child:
                                            _userSubmission!.imageUrl
                                                    .startsWith('assets/')
                                                ? Image.asset(
                                                  _userSubmission!.imageUrl,
                                                  fit: BoxFit.cover,
                                                  width: double.infinity,
                                                  height: double.infinity,
                                                )
                                                : Image.file(
                                                  File(
                                                    _userSubmission!.imageUrl,
                                                  ),
                                                  fit: BoxFit.cover,
                                                  width: double.infinity,
                                                  height: double.infinity,
                                                  errorBuilder: (
                                                    context,
                                                    error,
                                                    stackTrace,
                                                  ) {
                                                    return Center(
                                                      child: Column(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .center,
                                                        children: [
                                                          Icon(
                                                            Icons.check_circle,
                                                            color: Colors.green,
                                                            size: 48.sp,
                                                          ),
                                                          SizedBox(height: 8.h),
                                                          Text(
                                                            'Submitted',
                                                            style: TextStyle(
                                                              color:
                                                                  Colors.white,
                                                              fontSize: 16.sp,
                                                              fontFamily:
                                                                  GoogleFonts.mochiyPopOne()
                                                                      .fontFamily,
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                    );
                                                  },
                                                ),
                                      ),
                                      // 已提交标记
                                      Positioned(
                                        top: 16,
                                        right: 16,
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            horizontal: 12.w,
                                            vertical: 6.h,
                                          ),
                                          decoration: BoxDecoration(
                                            color: Colors.green,
                                            borderRadius: BorderRadius.circular(
                                              16.r,
                                            ),
                                          ),
                                          child: Text(
                                            'Submitted',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 12.sp,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                                  : Center(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Icon(
                                          MyIcons.iconAdd,
                                          size: 24.w,
                                          color: Colors.white,
                                        ),
                                        SizedBox(height: 8.h),
                                        Text(
                                          'Tap to select an image',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 14.sp,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                        ),
                      ),
                      SizedBox(height: 10.h),

                      // Eula
                      GestureDetector(
                        onTap: () {
                          WangYe.openUrl(
                            'https://www.freeprivacypolicy.com/live/d6a9a407-9d63-42af-9bc0-471389957c78',
                          );
                        },
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'EULA',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontFamily: GoogleFonts.inter().fontFamily,
                              fontWeight: FontWeight.w400,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: 80.h),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}
